package com.valsong.sandbox.mock.module;

import com.alibaba.jvm.sandbox.api.Information;
import com.alibaba.jvm.sandbox.api.Module;
import com.alibaba.jvm.sandbox.api.annotation.Command;
import com.alibaba.jvm.sandbox.api.resource.ModuleEventWatcher;
import com.google.inject.Injector;
import com.valsong.sandbox.mock.EventWatcherContext;
import com.valsong.sandbox.mock.GuiceBeanFactory;
import com.valsong.sandbox.mock.Mocker;
import org.kohsuke.MetaInfServices;

import javax.annotation.Resource;
import java.io.PrintWriter;
import java.util.Map;

import static com.valsong.sandbox.mock.constant.MockConstants.MOCK;
import static com.valsong.sandbox.mock.constant.MockConstants.MOCKER;
import static com.valsong.sandbox.mock.constant.MockConstants.MOCKER_AUTHOR;
import static com.valsong.sandbox.mock.constant.MockConstants.MOCKER_MODULE_NAME;
import static com.valsong.sandbox.mock.constant.MockConstants.MOCKER_VERSION;


/**
 * Mock模块
 *
 * @author Val Song
 */
@MetaInfServices(Module.class)
@Information(id = MOCKER, version = MOCKER_VERSION, author = MOCKER_AUTHOR)
public class MockerModule implements Mocker, Module {

    @Resource
    private ModuleEventWatcher moduleEventWatcher;

    @Command(MOCK)
    @Override
    public void mock(Map<String, String> param, PrintWriter printWriter) {
        try {
            Injector injector = GuiceBeanFactory.injector();
            EventWatcherContext eventWatcherContext = injector.getInstance(EventWatcherContext.class);
            eventWatcherContext.initialize(moduleEventWatcher, param, printWriter);
        } catch (Throwable throwable) {
            log.error(throwable.getMessage(), throwable);
            throw throwable;
        }
    }

    @Override
    public String moduleName() {
        return MOCKER_MODULE_NAME;
    }

}
